package com.atguigu.spzx.cloud.gateway.filter;

import io.netty.util.internal.StringUtil;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebSession;
import reactor.core.publisher.Mono;

/**
 * 认证权限过滤器
 *
 * 只需要纳入ioc容器就可使用
 */
@Component
public class AuthorizationFilter implements GlobalFilter , Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求参数如果提供这个参数合法请求，否则拒绝访问。
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        Mono<WebSession> session = exchange.getSession();
//        ApplicationContext applicationContext = exchange.getApplicationContext(); //获取ioc容器

        //MultiValueMap<String, String> queryParams = request.getQueryParams();
        //http://localhost:8222/api/user/findUserByUserId/1?age=22&age=23&username=zhangsan&username=lisi
        //List<String> username = request.getQueryParams().get("username");

        String username = request.getQueryParams().getFirst("username");
        if (!StringUtils.hasText(username)){
            response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return response.setComplete(); //请求完成，不放行,拒绝访问
        }

        System.out.println("放行前拦截--------------");

        Mono<Void> mono = chain.filter(exchange);

        System.out.println("放行之后拦截");
        return mono;

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
